package com.yand.thinkingInJava.thinkingInJava21.stopThread;


import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;


//睡眠阻塞
class SleepBlocked implements Runnable{

    @Override
    public void run() {
       try{
           TimeUnit.SECONDS.sleep(10);
       }catch (InterruptedException e){
           System.out.println("InterruptedException");
       }

       System.out.println("Exiting SleepBlocked.run()");
    }
}

class IOBlocked implements Runnable{

    private InputStream in;

    public IOBlocked(InputStream is){
        in = is;
    }

    @Override
    public void run() {
        try{
            System.out.println("Waiting for read()");
            in.read();
        }catch (IOException e){
            if(Thread.currentThread().isInterrupted()){
               System.out.println("Interrupted from block I/O");
            }else{
                throw new RuntimeException(e);
            }
        }
        System.out.println("Exiting IOBlocked.run()");
    }
}

class SynchronizedBlocked implements Runnable{

    public synchronized  void f(){
        while(true){
            Thread.yield();
        }
    }

    public SynchronizedBlocked(){

        new Thread(){

            public void run(){
                f();
            }


        }.start();
    }

    @Override
    public void run() {
         System.out.println("Trying to call f()");
         f();
         System.out.println("Exiting SynchronizedBlocked.run()");
    }
}


/**
 * interrupting 打断，用来打断线程，将线程的一个状态改为中断状态，如果有阻塞的代码 如 sleep wait 就会跳转到异常中...
 * 从而打断进程
 */
public class Interrupting {

    private static ExecutorService exec = Executors.newCachedThreadPool();


    static void test(Runnable r) throws InterruptedException{
        Future<?> f = exec.submit(r);
        TimeUnit.MILLISECONDS.sleep(100);
        System.out.println("Interrupting "+r.getClass().getName());
        f.cancel(true);
        System.out.println("Interrupt sent to "+r.getClass().getName());
    }

    public static void main(String [] args) throws Exception{
        //test(new SleepBlocked());
        //test(new IOBlocked(System.in));
        test(new SynchronizedBlocked());
        TimeUnit.SECONDS.sleep(3);
        //System.out.println("Aborting with System.exit(0)");
        //System.exit(0);
    }
}
